package org.kl.bf.web.basic;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.kl.bf.entity.basic.BasicFile;
import org.kl.bf.entity.basic.DocumentContent;
import org.kl.bf.entity.easyui.EasyuiGrid;
import org.kl.bf.service.basic.BasicFileService;
import org.kl.bf.service.basic.DocumentContentService;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

@Controller
@RequestMapping(value = "/basic/documentContent")
public class DocumentContentController extends BasicController {

	@Autowired
	private DocumentContentService documentContentService;
	@Autowired
	private BasicFileService basicFileService;

	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/helpDocumentList";
	}

	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "id") String sortType,
			@RequestParam(value = "order", defaultValue = "desc") String orderType, Model model, ServletRequest request) {
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		Page<DocumentContent> documentContents = documentContentService.getUserDocumentContent(searchParams,
				pageNumber, pageSize, sortType, orderType);
		EasyuiGrid grid = new EasyuiGrid();
		grid.setRows(documentContents.getContent());
		grid.setTotal((int) documentContents.getTotalElements());
		String result = jsonMapper.toJson(grid);
		return result;
	}

	@RequestMapping(value = "content", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String content(@RequestParam(value = "helpDocId") String helpDocId, Model model, ServletRequest request)
			throws Exception {
		String result = null;
		// Map<String,String> map=new HashMap<String,String>();
		if (StringUtils.isBlank(helpDocId)) {
			result = ajaxMsg("文档唯一标识获取失败，无法查看，请刷新重试", false, null);
		} else {
			DocumentContent documentContent = documentContentService.getDCByHelpDocId(helpDocId);

			if (documentContent != null) {
				String joinFileId = documentContent.getJoinFileId();
				if (StringUtils.isNotBlank(joinFileId)) {
					List<BasicFile> basicFileList = basicFileService.getBasicFileByJoinFileId(joinFileId);
					documentContent.setBasicFileList(basicFileList);
					documentContentService.saveDocumentContent(documentContent);
				}
				result = ajaxMsg("", true, documentContent);
			} else {
				result = ajaxMsg("没有相关内容,请添加相关内容！", false, null);
			}

		}
		return result;
	}

	// 删除附件关联
	@RequestMapping(value = "delBasicFile", method = RequestMethod.GET, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delBasicFile(@RequestParam(value = "basicFileId", defaultValue = "") String basicFileId,
			RedirectAttributes redirectAttributes, HttpSession session) {
		try {
			// notifyInfoService.deleteJoinFileId(joinFileId,receiverId);
			basicFileService.delJoinFileId(basicFileId);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除附件失败", true, null);
		}
		return ajaxMsg("删除附件成功", true, null);
	}

	@RequestMapping(value = "form/{helpDocId}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	public String from(@PathVariable(value = "helpDocId") String helpDocId, Model model) throws Exception {
		if (StringUtils.isBlank(helpDocId)) {
			model.addAttribute("error", "文档唯一标识获取失败，无法查看，请刷新重试");
		} else {
			DocumentContent documentContent = documentContentService.getDCByHelpDocId(helpDocId);
			if (documentContent != null) {
				model.addAttribute("documentContent", documentContent);
			} else {
				model.addAttribute("error", "没有相关内容");
			}

		}
		return "basic/documentContent";
		/*
		 * DocumentContent dcs =
		 * documentContentService.getDCByHelpDocId(helpDocId); return dcs;
		 */
	}

	// @RequiresPermissions("config:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("documentContent") DocumentContent documentContent,
			RedirectAttributes redirectAttributes, HttpSession session) {
		try {
			documentContentService.saveDocumentContent(documentContent);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("编辑失败[" + e.getMessage() + "]", false, null);
		}
		List<DocumentContent> documentContentList = documentContentService.getAllDocumentContent();
		for (DocumentContent c : documentContentList) {
			session.getServletContext().setAttribute(c.getId(), c.getHelpDocTag());
		}
		return ajaxMsg("编辑成功", true, null);
	}

	// @RequiresPermissions({ "config:delete", "config:update" })
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes, HttpSession session) {
		documentContentService.deleteDocumentContent(id);
		List<DocumentContent> documentContentList = documentContentService.getAllDocumentContent();
		for (DocumentContent c : documentContentList) {
			session.getServletContext().setAttribute(c.getId(), c.getHelpDocTag());
		}
		return ajaxMsg("删除成功", true, null);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getDocumentContent(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("documentContent", documentContentService.getDocumentContent(id));
		}
	}

}
